<template>
  <div v-loading="loading">
    <el-dialog
      :model-value="dialogVisible"
      title="余额充值"
      @close="closeDialog"
      :close-on-click-modal="false"
      center
      width="40%"
    >
      <el-form
        :model="form"
        :inline="true"
        :label-width="'120px'"
        style="margin-top: 30px"
      >
        <!-- <el-form-item label="选择支付方式">
                    <el-select v-model="form.recharge" placeholder="请选择支付方式" @change="rechargeTypeChange"
                        :popper-options="{ modifiers: [{ name: 'computeStyles', options: { adaptive: false } },], }"
                        style="width: 200px;">
                        <el-option label="充值余额" value="balance" />
                        <el-option label="扫码充值" value="code" />
                    </el-select>
                </el-form-item> -->
        <el-form-item label="输入金额">
          <div style="display: flex; gap: 20px">
            <el-input
              v-model="form.fee"
              placeholder="请输入充值金额"
              @input="onInputChange"
              style="width: 200px"
            />
            <el-button type="primary" @click="addfee">充值余额</el-button>
          </div>
        </el-form-item>
        <!-- 前端生成二维码 -->
        <div style="position: relative; margin-bottom: 10px">
          <QrcodeGenerator
            :text="!ismodel ? codeUrl : 'INVALID'"
            :size="200"
            level="H"
            style="z-index: 99"
            class="code-box"
            v-if="isShowCode"
          />
          <div class="model" v-if="timeLeft <= 0 && ismodel">
            <span>已失效</span>
          </div>
        </div>
        <!-- 显示二维码和倒计时 -->
        <div class="error-box">
          <!-- 当二维码显示且倒计时在进行时，显示倒计时 -->
          <div v-if="timeLeft > 0 && showCode">
            请在 <span>{{ minutes }}</span> 分
            <span>{{ seconds }}</span> 秒内完成支付
          </div>
          <!-- 当二维码失效或倒计时结束时，显示“刷新”按钮 -->
          <div v-if="showRefresh">
            二维码已失效，请
            <span class="refresh" @click="addfee">刷新</span> 重新支付
          </div>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, computed, Ref } from 'vue';
import { ElMessage } from 'element-plus';
import recharge from '@/modules';
// 接口api
const { addMoneyApi, payVerificationApi } = recharge;
const emit = defineEmits(['update:dialogVisible', 'paySuccess']);
// 前端生成二维码组件
import QrcodeGenerator from '@/components/QrcodeGenerator/index.vue';
// 组件加载效果
const loading = ref(false);
const showCode: Ref<boolean> = ref(false);
const showRefresh: Ref<boolean> = ref(false);
const codeUrl: Ref<string | null> = ref(null);
const timeLeft: Ref<number> = ref(0);
const ismodel: Ref<boolean> = ref(false);
const isShowCode: Ref<boolean> = ref(false);

// 定时器变量
let countdownInterval: number | null = null;
let checkPaymentInterval: number | null = null;
// 倒计时分和秒的计算
const minutes = computed(() => Math.floor(timeLeft.value / 60));
const seconds = computed(() => timeLeft.value % 60);

const { dialogVisible } = defineProps({
  dialogVisible: Boolean,
});

// form表单
const form = reactive({
  recharge: '',
  fee: '',
});
// 开始倒计时并轮询支付状态
const startCountdownAndCheckPayment = (out_trade_no: object) => {
  timeLeft.value = 5 * 60; // 5分钟倒计时

  // 清除现有的倒计时和支付状态检查
  if (countdownInterval !== null) clearInterval(countdownInterval);
  if (checkPaymentInterval !== null) clearInterval(checkPaymentInterval);

  // 开始新的倒计时
  countdownInterval = window.setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      if (countdownInterval !== null) clearInterval(countdownInterval); // 倒计时结束
      showCode.value = false; // 隐藏二维码
      ElMessage.error('二维码已失效');
      ismodel.value = true;
      isShowCode.value = true;
      showRefresh.value = true; // 隐藏二维码
      refreshQRCode(); // 倒计时结束时刷新二维码
    }
  }, 1000);

  // 开始轮询支付状态
  checkPaymentInterval = window.setInterval(async () => {
    const { code } = await payVerificationApi(out_trade_no);
    if (code === 20001) {
      return;
    } else if (code == 20000) {
      if (countdownInterval !== null) clearInterval(countdownInterval); // 停止倒计时
      if (checkPaymentInterval !== null) clearInterval(checkPaymentInterval); // 停止支付检查
      form.fee = '';
      showCode.value = false; // 隐藏二维码
      emit('update:dialogVisible', false);
      emit('paySuccess', true);
      ElMessage.success('支付成功');
    }
  }, 3000); // 每3秒轮询支付状态
};
// 刷新二维码
const refreshQRCode = async () => {
  if (countdownInterval !== null) clearInterval(countdownInterval); // 清除之前的倒计时
  if (checkPaymentInterval !== null) clearInterval(checkPaymentInterval); // 清除之前的支付状态轮询
  // await addfee(); // 调用addfee重新生成二维码并重新开始倒计时和轮询
};

// 下拉
// const rechargeTypeChange = async (value: string) => {
//   try {
//     loading.value = true;
//     // 扫码
//     if (value == 'code') {
//       form.fee = '';
//       // 调用接口获取二维码
//       const { data } = await rechargeApi(props.cardForm);
//       codeUrl.value = data.code_url;
//       if (codeUrl.value) {
//         showCode.value = true;
//       }
//     } else {
//       // 充值余额
//       showCode.value = true;
//     }
//   } catch (error) {
//     loading.value = false;
//     showCode.value = false;
//   } finally {
//     loading.value = false;
//   }
// };
// 充值余额
const addfee = async () => {
  showRefresh.value = false;
  ismodel.value = false;

  if (!form.fee) return ElMessage.error('请填写金额');
  try {
    loading.value = true;
    const { data } = await addMoneyApi({ fee: form.fee });
    if (data) {
      codeUrl.value = data.code_url;
      showCode.value = true;
      isShowCode.value = true;
      // emit('update:dialogVisible', false);
      startCountdownAndCheckPayment({ out_trade_no: data.out_trade_no }); // 开始倒计时和支付状态检查
    }
  } catch (error) {
    console.log(error);
    loading.value = false;
  } finally {
    loading.value = false;
  }
};

// 限制输入内容为正整数或最多两位小数，并禁止特殊字符
const onInputChange = (event: string) => {
  // 移除非数字和小数点的字符
  form.fee = event.replace(/[^\d.]/g, '');

  // 确保只有一个小数点
  if (form.fee.indexOf('.') !== form.fee.lastIndexOf('.')) {
    form.fee = form.fee.substring(0, form.fee.length - 1);
  }

  // 移除开头的多余的0，除非是"0."这种小数形式
  if (form.fee !== '' && form.fee[0] === '0' && form.fee[1] !== '.') {
    form.fee = form.fee.substring(1);
  }

  // 限制小数点后只能有两位小数
  const decimalIndex = form.fee.indexOf('.');
  if (decimalIndex >= 0) {
    form.fee = form.fee.substring(0, decimalIndex + 3);
  }

  // 确保输入的数字大于0
  if (parseFloat(form.fee) <= 0) {
    form.fee = '';
  }
};
// 关闭对话框并通知父组件
const closeDialog = () => {
  // 清除现有的倒计时和支付状态检查
  if (countdownInterval !== null) clearInterval(countdownInterval);
  if (checkPaymentInterval !== null) clearInterval(checkPaymentInterval);
  emit('paySuccess', false);
  emit('update:dialogVisible', false);
};

// 确认对话框操作
// const confirmDialog = () => {
//     emit('update:dialogVisible', false);
// };
</script>

<style scoped lang="scss">
.error-box {
  text-align: center;
  .refresh {
    cursor: pointer;
    color: blueviolet;
  }
}
.model {
  width: 200px;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #5f5e5e;
  position: absolute;
  top: 0;
  left: calc(50% - 100px);
  opacity: 0.5; /* 背景透明 */
  font-size: 20px;
  color: rgba(255, 255, 255, 1); /* 确保文本不透明 */
}
</style>
